<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use app\common\library\Sms;
use fast\Random;
use think\Request;
use think\Config;
use app\common\library\Upload;
use Exception;
use app\admin\model\personal\AccountLog;

/**
 * 订单接口
 */
class Order extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * @ApiTitle    (确认订单)
     * @ApiSummary  (确认订单)
     * @ApiMethod   (POST)
     * @ApiRoute    (api/Order/confirmOrder)
     * @ApiParams   (name="id", type="varchar", required=false, description="商品id")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 1,
    "msg": "ok",
    "time": "1627553755",
    "data": {
        'id':1
        'game':游戏
        'title':标题
        'server':区服
        'image':图片
        'type_name':类型
        'goods_type':类型id
        'price':售价
        'serverAll':全部区服
        'sku':信息

     * })
     */
    public function confirmOrder()
    {
        $token = $this->request->header('token');
        $this->is_login($token);
        $ids = Db::name('personal')->where('token',$token)->value('id');
        $user = Db::name('personal')->where('id',$ids)->find();
        if ($user['is_real'] != 1) {
            $this->error('未实名',[],101);
        }
        $id = $this->request->post('id');
        $res = Db::name('goods')
            ->field('id,goods_class_type,gameid,gamename,title,area,cross_id,server,goods_type,type_name,price,sku,info,is_appoint,area_id,is_safe,stock,method,coin_ratio,coin')
            ->where('id',$id)
            ->find();
        $image = Db::name('game')->where('id',$res['gameid'])->value('image');
        if (!empty($res['cross_id'])) {
            $map['cross'] = $res['cross_id'];
        }
        $map['status'] = 'normal';
        $map['game_id'] = $res['gameid'];
        $map['gt_id'] = 4;
        $res['serverAll'] = Db::name('game_info')
            ->field('id,name')
            ->where($map)
            ->select();
        $specs = Db::name('attr')->where('type',$res['type_name'])->value('value');
        $res['specs'] = $specs ? $specs : '万金';
	    //获取心意购费率
        $xinyigou_fee = DB::name("server")->where(['game_id'=>$res['gameid'],'game_type'=>$res['goods_type'],'safe'=>3,'method'=>$res['method']])->field('xyg_fee')->find();
        if(!$xinyigou_fee){
            $xinyigou_fee = DB::name("server")->where(['game_id'=>0,'safe'=>3,'method'=>$res['method']])->field("xyg_fee")->find();
        }
        if(!$xinyigou_fee) $xinyigou_fee['xyg_fee']='3/6/9';
        $res['xyg_fee'] = explode('/',$xinyigou_fee['xyg_fee']);
        $res['image'] = config('api_image_url') . $image;
        $res['sku'] = htmlspecialchars_decode($res['sku']);
        $res['sku'] = json_decode($res['sku'],true);
        $this->success('ok',$res);
    }



    /**
     * @ApiTitle    (下单)
     * @ApiSummary  (下单)
     * @ApiMethod   (POST)
     * @ApiRoute    (api/Order/order)
     * @ApiHeaders	(name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="good_id", type="varchar", required=false, description="商品id")
     * @ApiParams   (name="num", type="varchar", required=false, description="购买数量")
     * @ApiParams   (name="role", type="varchar", required=false, description="收货角色")
     * @ApiParams   (name="role_server", type="varchar", required=false, description="收货区服")
     * @ApiParams   (name="mobile", type="varchar", required=false, description="手机号")
     * @ApiParams   (name="qq", type="varchar", required=false, description="QQ号")
     * @ApiParams   (name="invite", type="varchar", required=false, description="推广码")
     * @ApiParams   (name="xyg", type="varchar", required=false, description="1 无  2 30天  3 60天  4 90天")
     * @ApiParams   (name="cipher", type="varchar", required=false, description="交易暗码")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 1,
    "msg": "支付",
    "time": "1627553755",
    "data": {
    'id':1

     * })
     */
    public function order()
    {
        $token = $this->request->header('token');
        $id = Db::name('personal')->where('token',$token)->value('id');
        if (empty($id)) {
            $this->error('请登录',[],401);
        }
        $post = $this->request->post();
        $user = Db::name('personal')->where('id',$id)->find();
        if ($user['is_real'] != 1) {
            $this->error('未实名',[],101);
        }
        $role = $post['role'] ? $post['role'] : '';
        $roleServer = $post['role_server'] ? $post['role_server'] : '';
        $rand = $id < 9999 ? mt_rand(100000, 99999999) : mt_rand(100, 99999);
        $sn = date('Yhis') . $rand;
        $id = str_pad($id, (18 - strlen($sn)), '0', STR_PAD_BOTH);
        $order_sn = $sn . $id;
        $goods = Db::name('goods')->where('id',$post['good_id'])->find();
        //添加分组，只有投诉咨询和一级客服可以分配
        $auth_group = DB::name("auth_group")->where(['name'=>['in',['投诉咨询','一级客服']]])->column('id');
        $auth_group_access = DB::name("auth_group_access")->where(['group_id'=>['in',$auth_group]])->column("uid");
        $admin_id = Db::name('admin')->where(['status'=>'normal','id'=>['in',$auth_group_access]])->orderRaw('Rand()')->value('id');
        //$admin_id = Db::name('admin')->where('status','normal')->orderRaw('Rand()')->value('id');
//        if ($goods['uid'] == 12) {
//            $this->error('此商品已售罄');
//        }
        if ($goods['stock'] - $post['num'] < 0) {
            $this->error('库存不足,无法操作',[],202);
        }
        if ($goods['uid'] == $user['id']) {
            $this->error('此商品是您发布,不可购买');
        }
        if ($goods['status'] != 1) {
            $this->error('此商品已下架');
        }
        if ($goods['is_appoint'] == 1) {
            if ($goods['cipher'] != $post['cipher']) {
                $this->error('交易暗码错误');
            }
        }
        /*
        $fee = Db::name('server')->where('id',2)->find();
        $fee1 = $goods['price'] / (1 + $fee['service']) * $fee['trade'];
        if ($fee1 < 1 && $post['xyg'] == 2) {
            $amount = $goods['price'] + 1;
        } else {
            if ($goods['is_safe'] == 3 && $post['xyg'] == 2) {
                $amount = $post['num']*$goods['price']*(1+$fee['service']);
            } else {
                $amount = $post['num']*$goods['price'];
            }
        }*/
        if($goods['is_safe'] == 3) {
            $fee = DB::name("server")->where(['game_id'=>$goods['gameid'],'game_type'=>$goods['goods_type'],'safe'=>2,'method'=>$goods['method']])->find();
        } else {
            $fee = DB::name("server")->where(['game_id'=>$goods['gameid'],'game_type'=>$goods['goods_type'],'safe'=>$goods['is_safe'],'method'=>$goods['method']])->find();
        }

        if(!$fee){
            $fee = DB::name("server")->where(['game_id'=>$goods['gameid'],'game_type'=>$goods['goods_type'],'safe'=>'2','method'=>$goods['method']])->find();
            if(!$fee){
                $fee = Db::name('server')->where('id',1)->find();
            }
        }
        // if ($fee['service'] == 0) {
        //     $fee['service'] = 1;
        // }
        // // $fee1 = $goods['price'] * $post['num'] * $fee['service'] * $fee['trade'];
        // $fee1 = $goods['prices'] < 
        // if ($fee1 < 1 && $post['xyg'] != 1) {
        //     $amount = $goods['price']*$post['num'] + 1;
        // } else {
            //暂时写死，如果需要活的，直接去server表中xyg_fee即可
            if($goods['is_safe'] == 3){
                if($goods['goods_class_type'] == 1){
                    //心意购 分30天、60天、90天
                    if($post['xyg']){
                        switch ($post['xyg']){
                            case 2:
                                $xyg_fee = '0.03';
                                break;
                            case 3:
                                $xyg_fee = '0.06';
                                break;
                            case 4:
                                $xyg_fee = '0.09';
                                break;
                            default:
                                $xyg_fee = '0';
                                break;
                        }
                    }else{
                        $xyg_fee = '0';
                    }
                }else{
                    //心意购 分30天、60天、90天
                    if($post['xyg']){
                        switch ($post['xyg']){
                            case 2:
                                $xyg_fee = '0.01';
                                break;
                            case 3:
                                $xyg_fee = '0.02';
                                break;
                            case 4:
                                $xyg_fee = '0.03';
                                break;
                            default:
                                $xyg_fee = '0';
                                break;
                        }
                    }else{
                        $xyg_fee = '0';
                    }
                }

                $fee['service'] = $xyg_fee;
                $amount = $post['num']*$goods['price'];
                $extra_fee = $post['num']*$goods['price']*$fee['service'];
                if($extra_fee < 1) $extra_fee = 1;
                $amount = $amount+$extra_fee;
            }else if($goods['is_safe'] == 2){
                //无服务 心意购费率是0
                $amount = $post['num']*$goods['price'];
                $fee['service'] = 0;
            }else{
                //包赔 没有手续费
                $amount = $post['num']*$goods['price'];
            }
        // }

        $white_list = array();
        if($goods['goods_class_type'] != 1){
            //查询白名单
            $user_mobile = DB::name("personal")->where("id",$goods['uid'])->value("mobile");
            $white_list = DB::name("order_whitelist")->where(['game_id'=>$goods['gameid'],'mobile'=>$user_mobile])->find();

        }
        if($white_list){
            //卖家在白名单，则手续费为0
            $fee['service'] = 0;
            $fee['trade'] = 0;
            $amount = $post['num']*$goods['price'];
            $service = $post['num']*$goods['prices']*$fee['service'];
            $trade = $post['num']*$goods['prices']*$fee['trade'];
        }else{
            $service = $post['num']*$goods['prices']*$fee['service'];
            $trade = $post['num']*$goods['prices']*$fee['trade'];
            if($goods['goods_class_type'] != 1){
                if($trade<1) $trade = 1;
            }else{
                if($trade<4) $trade = 4;
            }
        }

//        $service = $post['num']*$goods['price']*$fee['service'];
//        $trade = $post['num']*$goods['price']*$fee['trade'];

        $res = [
            'order_class_type'  =>  $goods['goods_class_type'],
            'uid'   =>  $goods['uid'],
            'buyid'   =>  $user['id'],
            'account'   =>  $user['account'],
            'order_sn'  =>  $order_sn,
            'goods_id'   =>  $post['good_id'],
            'num'   =>  $post['num'],
            'mobile'    =>  $post['mobile'],
            'invite'    =>  $post['invite'],
            'xyg'    =>  $post['xyg'],
            'role'  =>  $role,
            'role_server'  =>  $roleServer,
            'qq'    =>  $post['qq'],
            'image' =>  $goods['image'],
            'title' =>  $goods['title'],
            'game'  =>  $goods['gamename'],
            'game_id'  =>  $goods['gameid'],
            'plat_id'  =>  $goods['plat_id'],
            'plat'  =>  $goods['plat'],
            'deposit'    =>  $goods['is_pei'],
            'area_id'    =>  $goods['area_id'],
            'area'    =>  $goods['area'],
            'server_id'    =>  $goods['server_id'],
            'server'    =>  $goods['server'],
            'cross_id' =>  $goods['cross_id'],
            'cross' =>  $goods['cross'],
            'type_name'    =>  $goods['type_name'],
            'goods_type'    =>  $goods['goods_type'],
            'buy_type'    =>  $goods['method'],
            'type'  =>  $goods['goods_type'],
            'price' =>  $goods['prices'],
            'amount'    =>  $amount,
            'ontime'    =>  time(),
            'status'    =>  1,
            'complaint'    =>  0,
            'admin_id'  =>  $admin_id,
            'fee'=>$service,
            'daifa_fee'=>$trade,
        ];
        $data = Db::name('order')->insertGetId($res);
        if ($data) {
            $easy = new Goeasy();
            $msg = '您有新订单了!';
            $easy->sendToAdmin($admin_id,$msg);
            Db::name('goods')->where('id',$post['good_id'])->setDec('stock',$post['num']);
            $ck = Db::name('goodsinfo')->where('goods_id',$post['good_id'])->where('status',0)->limit($post['num'])->select();
            foreach ($ck as $k=>$v) {
                Db::name('goodsinfo')->where('id',$v['id'])->update(['status'=>1,'order_id'=>$data]);
            }
            $this->success('下单成功',$data);
        } else {
            $this->error(__('添加失败'));
        }
    }


    /**
     * @ApiTitle    (订单发货/取消)
     * @ApiSummary  (订单发货/取消)
     * @ApiMethod   (POST)
     * @ApiRoute    (api/Order/flow)
     * @ApiParams   (name="id", type="varchar", required=true, description="订单id")
     * @ApiParams   (name="type", type="varchar", required=true, description="7取消  3发货")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 1,
    "msg": "操作成功",
    "time": "1627547401",

     * })

     */
    public function flow()
    {
        $id = $this->request->post('id');
        $type = $this->request->post('type');
        $order = Db::name('order')->where('id',$id)->find();
        if ($order['status'] != 2) {
            $this->error('此商品已发货,请误操作');
        }
        try {
            Db::startTrans();
            if ($type == 7) {
                //取消订单
                $idss = 1988;
                $rand = $id < 9999 ? mt_rand(100000, 99999999) : mt_rand(100, 99999);
                $sn = date('Yhis') . $rand;
                $idss = str_pad($idss, (18 - strlen($sn)), '0', STR_PAD_BOTH);
                $refund_sn = $sn . $idss;
                $root_path = $this->request->root(true);
                // if($order['payway'] == '微信'){
                //     $refund_url = str_replace('/BfcTyWlLqd.php','',$root_path).'/api/pay/notify_wechat_refund';
                //     $epay = \addons\epay\library\Service::refund_wechat('0.1',$order['order_sn'],$refund_sn,'wechat','退款',$refund_url,'','app');
                //     $re['s1'] = 1;
                // }else if($order['payway'] == '支付宝'){
                //     $epay = \addons\epay\library\Service::refund_ali('0.1',$order['order_sn'],$refund_sn,'alipay','退款','','','app');
                //     if($epay['code'] == 10000){
                //         $uinfo = DB::name('personal')->where(['id'=>$order['buyid']])->field('balance,jy_balance')->find();
                //         $log = new AccountLog();
                //         $res = $log->addAccountLog($order['buyid'], '+'.$order['amount'], 5, '后台客服撤单', 1,'',1);
                //         $re['s1'] = Db::name('order')->where('id',$id)->update(['status'=>7]);
                //     }else{
                //         $this->error("支付宝退款异常，请联系技术人员查看");
                //     }
                // }else{
                    $re['s1'] = Db::name('order')->where('id',$id)->update(['status'=>7]);
                    $re['s2'] = Db::name('personal')->where('id',$order['buyid'])->setInc('balance',$order['amount']);
                    $re['s3'] = Db::name('goods')->where('id',$order['goods_id'])->setInc('stock',$order['num']);
                // }
                
            } elseif ($type == 3) {
                $re['s1'] = Db::name('order')->where('id',$id)->update(['status'=>3,'sendtime'=>time()]);
                $send = new Send();
                $re['s2'] = $send->send($order['mobile'],1);
            }

            //任意一个表写入失败都会抛出异常：
            if (in_array('0', $re)) {
                throw new Exception('操作失败');
            }
            // 提交事务
            Db::commit();
            throw new Exception('操作成功');
        } catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            //注意：我们做了回滚处理
            $this->error($e->getMessage());
        }
    }


    /**
     * @ApiTitle    (订单管理订单取消)
     * @ApiSummary  (订单管理订单取消)
     * @ApiMethod   (POST)
     * @ApiRoute    (api/Order/flows)
     * @ApiParams   (name="id", type="varchar", required=true, description="订单id")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 1,
    "msg": "操作成功",
    "time": "1627547401",

     * })

     */
    public function flows()
    {
        $id = $this->request->post('id');
        $order = Db::name('order')->where('id',$id)->find();
        try {
            Db::startTrans();

            $re['s1'] = Db::name('order')->where('id',$id)->update(['status'=>7]);
            $re['s2'] = Db::name('goods')->where('id',$order['goods_id'])->setInc('stock',$order['num']);


            //任意一个表写入失败都会抛出异常：
            if (in_array('0', $re)) {
                throw new Exception('操作失败');
            }
            // 提交事务
            Db::commit();
            throw new Exception('操作成功');
        } catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            //注意：我们做了回滚处理
            $this->error($e->getMessage());
        }
    }


    /**
     * @ApiTitle    (订单支付页面)
     * @ApiSummary  (订单支付页面)
     * @ApiMethod   (POST)
     * @ApiRoute    (api/Order/confirmPay)
     * @ApiParams   (name="id", type="varchar", required=true, description="订单id")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 1,
    "msg": "",
    "time": "1627547401",
    "data": {
        "id": 订单id,
        "order_sn": "订单号",
        "title": "标题",
        "server": "区服",
        "price": "价格"
    }
     * })

     */
    public function confirmPay()
    {
        $token = $this->request->header('token');
        $id = Db::name('personal')->where('token',$token)->value('id');
        $this->is_login($token);
        $oid = $this->request->post('id');
        $res = Db::name('order')->field('id,order_sn,title,server,amount')->where('id',$oid)->find();
        $user = Db::name('personal')->where('id',$id)->find();
        $res['balance'] = $user['balance'];
        $res['mobile'] = $user['mobile'];

        $this->success('ok',$res);
    }

    /**
     * @ApiTitle    (订单支付)
     * @ApiSummary  (订单支付)
     * @ApiMethod   (POST)
     * @ApiRoute    (api/Order/orderPay)
     * @ApiParams   (name="id", type="varchar", required=true, description="订单id")
     * @ApiParams   (name="type", type="varchar", required=true, description="支付类型 微信:wechat 支付宝:alipay)
     * @ApiParams   (name="method", type="varchar", required=true, description="app端：app")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 1,
    "msg": "",
    "time": "1627547401",
    "data": {

    }
     * })

     */

    public function orderPay()
    {
        $id = $this->request->post('id');
        $type = $this->request->post('type');
        $method = $this->request->post('method');
        $method = $method ? $method : "web";
        $order = Db::name('order')->where('id',$id)->find();
//        $amount = $order['amount'];
        $amount = 0.1;
        $orderid = $order['order_sn'];
        // $title = "780g";
        $title = '您在购买：'.$order['title'];
        $notifyurl = $this->request->root(true).'/addons/epay/index/notifyx/paytype/' . $type;
        $returnurl = $this->request->root(true) . '/addons/epay/index/returnx/paytype/' . $type . '/out_trade_no/' . $orderid;
//        $method = $method;
        $a = \addons\epay\library\Service::submitOrder($amount,$orderid,$type,$title,$notifyurl,$returnurl,$method);
        if ($method == 'app') {
            $this->success('ok',$a);
        } else {
            return $a;
        }
    }




    /**
     * @ApiTitle    (余额支付)
     * @ApiSummary  (余额支付)
     * @ApiMethod   (POST)
     * @ApiRoute    (api/Order/coinPay)
     * @ApiHeaders	(name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="varchar", required=true, description="订单id")
     * @ApiParams   (name="mobile", type="varchar", required=true, description="手机号")
     * @ApiParams   (name="captcha", type="varchar", required=true, description="验证码")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 1,
    "msg": "支付成功",
    "time": "1627547401",
    "data": {

    }
     * })

     */
    public function coinPay()
    {
        $token = $this->request->header('token');
        $id = Db::name('personal')->where('token',$token)->value('id');
        //添加分组，只有投诉咨询和一级客服可以分配
        $auth_group = DB::name("auth_group")->where(['name'=>['in',['投诉咨询','一级客服']]])->column('id');
        $auth_group_access = DB::name("auth_group_access")->where(['group_id'=>['in',$auth_group]])->column("uid");
        $admin_id = Db::name('admin')->where(['status'=>'normal','id'=>['in',$auth_group_access]])->orderRaw('Rand()')->value('id');
        $this->is_login($token);
        $ids = $this->request->post('id');
        file_put_contents('yue.log',$ids);
        $user = Db::name('personal')->where('id',$id)->find();
	    $balance = $user['balance'];
        $order = Db::name('order')->where('id',$ids)->find();
        $goods = Db::name('goods')->where('id',$order['goods_id'])->find();
        if ($balance - $order['amount'] < 0) {
            $this->error('余额不足');
        }
        if ($order['status'] == 9) {
            $this->error('订单已超时,请重新下单');
        }

        if ($order['status'] != 1) {
            $this->error('订单已支付');
        }

        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!Sms::check($mobile, $captcha, 'coinpay')) {
            $this->error(__('请填写正确的验证码'));
        }
        try {
            Db::startTrans();
            if ($goods['goods_class_type'] == 1) {
                $ret1 = [
                    'uid'   =>  $user['id'],
                    'log_sn'    =>  date('YmdHis') . rand(10000000,99999999),
                    'money' =>  '-'.$order['amount'],
                    'type'  =>  1,
                    'content'   =>  '消费',
                    'createtime'    =>  time(),
                    'arrivaltime'   =>  time(),
                    'status'    =>  1
                ];
                $re['s1'] = Db::name('order')->where('id',$ids)->update(['status'=>11,'paytime'=>time(),'payway'=>'余额']);
                $re['s2'] = Db::name('account_log')->insert($ret1);
                $re['s3'] = Db::name('personal')->where('id',$user['id'])->setDec('balance',$order['amount']);
                $easy = new Goeasy();
                $msg = '您有待验证的订单了!';

                $re['s5'] = $easy->sendToAdmin($admin_id,$msg);
            } else {
                $ret1 = [
                    'uid'   =>  $user['id'],
                    'log_sn'    =>  date('YmdHis') . rand(10000000,99999999),
                    'money' =>  '-'.$order['amount'],
                    'type'  =>  1,
                    'content'   =>  '消费',
                    'createtime'    =>  time(),
                    'arrivaltime'   =>  time(),
                    'status'    =>  1
                ];
                if ($goods['method'] == 3) {
	                $re['s1'] = Db::name('order')->where('id',$ids)->update(['status'=>5,'paytime'=>time(),'payway'=>'余额']);
                } else {
	                $re['s1'] = Db::name('order')->where('id',$ids)->update(['status'=>2,'paytime'=>time(),'payway'=>'余额']);
                }
                $re['s2'] = Db::name('account_log')->insert($ret1);
                $re['s3'] = Db::name('personal')->where('id',$user['id'])->setDec('balance',$order['amount']);
                $send = new Send();
                $re['s4'] = $send->send($goods['mobile'],2);
                $easy = new Goeasy();
                $msg = '您有待验证的订单了!';
                $re['s5'] = $easy->sendToAdmin($admin_id,$msg);
            }

            //任意一个表写入失败都会抛出异常：
            if (in_array('0', $re)) {
                throw new Exception('支付失败');
            }
                // 提交事务
            Db::commit();
        } catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            //注意：我们做了回滚处理，所以id为1039的数据还在
            $this->error($e->getMessage());
        }
        $this->success('支付成功');
    }

    public function getAount_new($game_id,$game_type,$amount, $type, $safe, $xyg, $method){
        $map['safe'] = $safe;
        $map['type'] = $type;
//        $map['xyg'] = $xyg;
        $map['method'] = $method;
        $map['game_id'] = $game_id;
        $map['game_type'] = $game_type;
        $fee = Db::name('server')->where($map)->find();
        if(!$fee){
            $fee = DB::name("server")->where('id', 1)->find();
        }
        $aa = $amount*$fee['trade'];
        if($aa < 1){
            $fee = 1;
        }else{
            $fee = $amount + $aa;
        }
        return $fee;
    }

    /**
     * @ApiTitle    (确认收货)
     * @ApiSummary  (确认收货)
     * @ApiMethod   (POST)
     * @ApiRoute    (api/Order/orderOk)
     * @ApiParams   (name="id", type="varchar", required=true, description="订单id")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 1,
    "msg": "确认收货成功",
    "time": "1627547401",
    "data": {

    }
     * })
     */
    public function orderOk()
    {
        $id = $this->request->post('id');
        $order = Db::name('order')->where('id',$id)->find();
        $goods = Db::name('goods')->where('id',$order['goods_id'])->find();
        $am = $order['price'] * $order['num'];

        $white_list = array();
        if($goods['goods_class_type'] != 1){
            //查询白名单
            $user_mobile = DB::name("personal")->where("id",$goods['uid'])->value("mobile");
            $white_list = DB::name("order_whitelist")->where(['game_id'=>$goods['gameid'],'mobile'=>$user_mobile])->find();
        }

        if($white_list){
            //卖家在白名单，则手续费为0
            $amount = $am;
        }else{
//            $amount = $this->getAmount($am,$goods['goods_class_type'],$goods['is_safe'],$order['xyg'],$goods['method']);
            $amount = $this->getAount_new($order['game_id'],$order['goods_type'],$am,$goods['goods_class_type'],$goods['is_safe'],$order['xyg'],$goods['method']);
        }
        if ($order['status'] == 5) {
            $this->error('该订单已完成');
        }
        if ($order['status'] != 3) {
            $this->error('该订单未发货');
        }
        try {
            Db::startTrans();
            if ($goods['goods_class_type'] == 1) {
                $re['s1'] = Db::name('order')->where('id',$id)->update(['status'=>8]);
            } else {
                $re['s1'] = Db::name('order')->where('id',$id)->update(['status'=>5,'overtime'=>time()]);
                $ret2 = [
                    'uid'   =>  $order['uid'],
                    'log_sn'    =>  date('YmdHis') . rand(10000000,99999999),
                    'money' =>  '+'.$amount,
                    'type'  =>  2,
                    'content'   =>  '售得',
                    'createtime'    =>  time(),
                    'arrivaltime'   =>  time(),
                    'status'    =>  1
                ];
                $re['s2'] = Db::name('account_log')->insert($ret2);
                $re['s3'] = Db::name('personal')->where('id',$order['uid'])->setInc('balance',$amount);
            }
            //任意一个表写入失败都会抛出异常：
            if (in_array('0', $re)) {
                throw new Exception('确认收货失败');
            }
            // 提交事务
            Db::commit();
        } catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            //注意：我们做了回滚处理，所以id为1039的数据还在
            $this->error($e->getMessage());
        }
        $this->success('确认收货成功');
    }

    /**
     * @ApiTitle    (获取账号信息)
     * @ApiSummary  (获取账号信息)
     * @ApiMethod   (POST)
     * @ApiRoute    (api/Order/getAccount)
     * @ApiParams   (name="id", type="varchar", required=true, description="订单id")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 1,
    "msg": "ok",
    "time": "1627547401",
    "data": {

    }
     * })

     */
    public function getAccount()
    {
        $id = $this->request->post('id');
        $order = Db::name('order')->where('id',$id)->find();

        if ($order['order_class_type'] == 3) {
	        $res = Db::name('goodsinfo')->field('id,cdkey,pwd')->where('order_id',$order['id'])->where('status',1)->select();
        } else {
	        $res = Db::name('goods')->field('g_account,g_password,second_pwd,ware_pwd,storage')->where('id',$order['goods_id'])->find();
        }
	    if (empty($res)) {
		    $this->error('没有账号密码');
	    }
        $this->success('ok',$res);
    }



    /**
     * @ApiTitle    (用户点击去确认)
     * @ApiSummary  (用户点击去确认)
     * @ApiMethod   (POST)
     * @ApiRoute    (api/Order/toBeConfirmed)
     * @ApiParams   (name="id", type="varchar", required=true, description="订单id")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 1,
    "msg": "ok",
    "time": "1627547401",
    "data": {

    }
     * })

     */
    public function toBeConfirmed()
    {
        $id = $this->request->post('id');
        //添加分组，只有投诉咨询和一级客服可以分配
        $auth_group = DB::name("auth_group")->where(['name'=>['in',['投诉咨询','一级客服']]])->column('id');
        $auth_group_access = DB::name("auth_group_access")->where(['group_id'=>['in',$auth_group]])->column("uid");
        $admin_id = Db::name('admin')->where(['status'=>'normal','id'=>['in',$auth_group_access]])->orderRaw('Rand()')->value('id');
        $type = Db::name('order')->where('id',$id)->value('order_class_type');
        if ($type==2) {
            $this->error('商品属于金币不可操作');
        }
        $data = Db::name('order')->where('id',$id)->update(['status'=>2]);
        if ($data) {
            $easy = new Goeasy();
            $msg = '您有待发货的订单了!';
            $easy->sendToAdmin($admin_id,$msg);
            $this->success('确认成功');
        } else {
            $this->error('确认失败');
        }
    }



    /**
     * @ApiTitle    (获取客服截图)
     * @ApiSummary  (获取客服截图)
     * @ApiMethod   (POST)
     * @ApiRoute    (api/Order/getScreenshot)
     * @ApiParams   (name="id", type="varchar", required=true, description="订单id")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 1,
    "msg": "ok",
    "time": "1627547401",
    "data": {

    }
     * })

     */
    public function getScreenshot()
    {
        $id = $this->request->post('id');
        $res = Db::name('order')->field('id,kf_images')->where('id',$id)->find();
        if (!empty($res['kf_images'])) {
            $res['kf_images'] = str_replace('/uploads',config('api_image_url').'/uploads',$res['kf_images']);
            $this->success('ok',$res);
        } else {
            $this->error('等待客服上传截图');
        }
    }


}
